package kr.co.skplanet.commute.controller.web;

import java.util.ArrayList;
import java.util.List;

import kr.co.skplanet.commute.dto.CalDTO;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MeController {
	// /me

	@RequestMapping(value = "/me", method = RequestMethod.GET)
	public String me(Model model) {
		model.addAttribute("name", "��만��");
		model.addAttribute("age", 50);
		return "me";
	}

	@RequestMapping(value = "/gugu", method = RequestMethod.GET)
	public String gugudan(
			@RequestParam(value = "dan", defaultValue = "5", required = false) int dan,
			Model model) {
		List<String> five = new ArrayList<String>();

		for (int i = 1; i < 10; i++) {
			five.add(dan + " * " + i + " = " + (dan * i));
		}

		model.addAttribute("dan", dan);
		model.addAttribute("five", five);
		return "gugu";
	}

	@RequestMapping(value = "/calForm", method = RequestMethod.GET)
	public String calform(
			Model model
	) {
		return "calForm";
	}
	@RequestMapping(value = "/calForm2", method = RequestMethod.GET)
	public String calform2(
			Model model
	) {
		return "calForm2";
	}

	@RequestMapping(value = "/cal", method = RequestMethod.POST)
	public String cal(
			@RequestParam(value = "left", required=true) int left,
			@RequestParam(value = "oper", required=true) String oper,
			@RequestParam(value = "right", required=true) int right, 
			Model model) {
		String result = left + " " + oper + " " + right;

		try {
			if (oper.equals("+")) {
				result = result + " = " + (left + right);
			} else if (oper.equals("-")) {
				result = result + " = " + (left - right);
			} else if (oper.equals("*")) {
				result = result + " = " + (left * right);
			} else if (oper.equals("/")) {
				int toException = left / right;
				result = result + " = " + ((double)left / (double)right);
			}
		} catch (ArithmeticException ex) {
			result = "0�쇰� ��� ��������.";
		}

		model.addAttribute("result", result);
		return "cal";
	}
	
	@RequestMapping(value = "/cal2", method = RequestMethod.POST)
	public String cal2(
			@ModelAttribute CalDTO calDTO,
			Model model) {
		calDTO.setResult();

		return "cal2";
	}

} // Controller